package file

import (
	"bufio"
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
)

// Mkdir 创建目录
func Mkdir(name string) error {
	return os.MkdirAll(name, os.ModePerm)
}

// Exist 是否存在
func Exist(fileName string) bool {
	_, err := os.Stat(fileName)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

// Copy 复制文件
func Copy(source, dist string) (int64, error) {
	src, err := os.Open(source)
	if err != nil {
		return 0, err
	}
	defer src.Close()
	dst, err := os.Create(dist)
	if err != nil {
		return 0, err
	}
	defer dst.Close()
	return io.Copy(dst, src)
}

// DirFiles 获取目录文件
func DirFiles(dir string) ([]string, error) {
	dir, err := filepath.Abs(dir)
	if err != nil {
		return nil, err
	}
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil, err
	}
	values := make([]string, 0)
	for _, file := range files {
		fileName := file.Name()
		if file.IsDir() {
			continue
		}
		values = append(values, dir+"/"+fileName)
	}
	return values, nil
}

// ReaderLine 按行读取内容
func ReaderLine(reader io.Reader, handle func([]byte) error) error {
	body := bufio.NewReader(reader)
	line, err := body.ReadBytes('\n')
	for err == nil {
		line = bytes.TrimRight(line, "\n")
		if len(line) > 0 {
			if line[len(line)-1] == 13 {
				line = bytes.TrimRight(line, "\r")
			}
			if err = handle(line); err != nil {
				return err
			}
		}
		line, err = body.ReadBytes('\n')
	}
	if len(line) > 0 {
		if err := handle(line); err != nil {
			return err
		}
	}
	if err == io.EOF {
		return nil
	}
	return err
}
